package router

import (
	"broker/interface/iserver"
	messageID "broker/struct/common/message_id"
	"sync"
)

type RouterTable struct {
	routers map[byte]iserver.IRouter
}

var routers = &RouterTable{}
var once sync.Once
func NewRouterTable() iserver.IRouterTable {
	once.Do(func() {
		routers = &RouterTable{
			routers: make(map[byte]iserver.IRouter),
		}
		///初始化路由表
		routers.AddRouter(messageID.Connect, NewConnectRouter())
		routers.AddRouter(messageID.DisConnect, NewDisConnectRouter())
		routers.AddRouter(messageID.PingReq, NewPingRouter())
		routers.AddRouter(messageID.Publish, NewPublishRouter())
		routers.AddRouter(messageID.Subscribe, NewSubScribeRouter())
		routers.AddRouter(messageID.UnSubscribe, NewUnSubscribeRouter())
	})
	return routers
}

func (rt *RouterTable) AddRouter(msgID byte, router iserver.IRouter) {
	rt.routers[msgID] = router
}

func (rt *RouterTable) AddRouters(routers map[byte]iserver.IRouter) {
	rt.routers = routers
}
func (rt *RouterTable) GetRouter(msgID byte) (iserver.IRouter, bool) {
	handle, ok := rt.routers[msgID]
	return handle, ok
}
func (rt *RouterTable) GetRouters() map[byte]iserver.IRouter {
	return rt.routers
}
func (rt *RouterTable) DeleteRouter(msgID byte) {
	delete(rt.routers, msgID)
}
func (rt *RouterTable) ClearRouters() {
	rt.routers = make(map[byte]iserver.IRouter)
}
